package com.ruoyi.gd.invoice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gd.fj.domain.vo.ZFujianVo;
import com.ruoyi.gd.fj.service.IZFujianService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.gd.invoice.domain.bo.ZInvoiceBo;
import com.ruoyi.gd.invoice.domain.vo.ZInvoiceVo;
import com.ruoyi.gd.invoice.domain.ZInvoice;
import com.ruoyi.gd.invoice.mapper.ZInvoiceMapper;
import com.ruoyi.gd.invoice.service.IZInvoiceService;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 发票Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-24
 */
@RequiredArgsConstructor
@Service
public class ZInvoiceServiceImpl implements IZInvoiceService {

    @Value("${upload.path}")
    private String uploadPath;

    private final ZInvoiceMapper baseMapper;

    @Autowired
    private IZFujianService zfujianService;

    public static final RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
        .setConnectionRequestTimeout(5000).build();

    /**
     * 查询发票
     */
    @Override
    public ZInvoiceVo queryById(String number){
        return baseMapper.selectVoById(number);
    }

    /**
     * 查询发票列表
     */
    @Override
    public TableDataInfo<ZInvoiceVo> queryPageList(ZInvoiceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZInvoice> lqw = buildQueryWrapper(bo);
        Page<ZInvoiceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询发票列表
     */
    @Override
    public List<ZInvoiceVo> queryList(ZInvoiceBo bo) {
        LambdaQueryWrapper<ZInvoice> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZInvoice> buildQueryWrapper(ZInvoiceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZInvoice> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), ZInvoice::getTitle, bo.getTitle());
        lqw.like(StringUtils.isNotBlank(bo.getMachineNumber()), ZInvoice::getMachineNumber, bo.getMachineNumber());
        lqw.like(StringUtils.isNotBlank(bo.getCode()), ZInvoice::getCode, bo.getCode());
        lqw.eq(bo.getKprq() != null, ZInvoice::getKprq, bo.getKprq());
        lqw.like(StringUtils.isNotBlank(bo.getChecksum()), ZInvoice::getChecksum, bo.getChecksum());
        lqw.like(StringUtils.isNotBlank(bo.getBuyerName()), ZInvoice::getBuyerName, bo.getBuyerName());
        lqw.like(StringUtils.isNotBlank(bo.getBuyerCode()), ZInvoice::getBuyerCode, bo.getBuyerCode());
        lqw.like(StringUtils.isNotBlank(bo.getBuyerAddress()), ZInvoice::getBuyerAddress, bo.getBuyerAddress());
        lqw.like(StringUtils.isNotBlank(bo.getBuyerAccount()), ZInvoice::getBuyerAccount, bo.getBuyerAccount());
        lqw.like(StringUtils.isNotBlank(bo.getPassword()), ZInvoice::getPassword, bo.getPassword());
        lqw.eq(bo.getAmount() != null, ZInvoice::getAmount, bo.getAmount());
        lqw.eq(bo.getTaxAmount() != null, ZInvoice::getTaxAmount, bo.getTaxAmount());
        lqw.like(StringUtils.isNotBlank(bo.getTotalAmountString()), ZInvoice::getTotalAmountString, bo.getTotalAmountString());
        lqw.eq(bo.getTotalAmount() != null, ZInvoice::getTotalAmount, bo.getTotalAmount());
        lqw.like(StringUtils.isNotBlank(bo.getSellerName()), ZInvoice::getSellerName, bo.getSellerName());
        lqw.like(StringUtils.isNotBlank(bo.getSellerCode()), ZInvoice::getSellerCode, bo.getSellerCode());
        lqw.like(StringUtils.isNotBlank(bo.getSellerAddress()), ZInvoice::getSellerAddress, bo.getSellerAddress());
        lqw.like(StringUtils.isNotBlank(bo.getSellerAccount()), ZInvoice::getSellerAccount, bo.getSellerAccount());
        lqw.like(StringUtils.isNotBlank(bo.getPayee()), ZInvoice::getPayee, bo.getPayee());
        lqw.like(StringUtils.isNotBlank(bo.getReviewer()), ZInvoice::getReviewer, bo.getReviewer());
        lqw.like(StringUtils.isNotBlank(bo.getDrawer()), ZInvoice::getDrawer, bo.getDrawer());
        lqw.like(StringUtils.isNotBlank(bo.getType()), ZInvoice::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增发票
     */
    @Override
    public Boolean insertByBo(ZInvoiceBo bo) {
        ZInvoice add = BeanUtil.toBean(bo, ZInvoice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setNumber(add.getNumber());
        }
        return flag;
    }

    /**
     * 修改发票
     */
    @Override
    public Boolean updateByBo(ZInvoiceBo bo) {
        ZInvoice update = BeanUtil.toBean(bo, ZInvoice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZInvoice entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除发票
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 解析附件
     * @return
     */
    @Override
    public int jxFj(String id) {
        String[] split = id.split(",");
        for (String fjId  : split) {
            ZFujianVo fjVo = zfujianService.queryById(fjId);
            File file = new File(uploadPath + fjVo.getFjpath());
            try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();) {
                HttpUriRequest request = new HttpGet(fjVo.getFjpath());
                try (CloseableHttpResponse response = httpclient.execute(request)) {
                    HttpEntity entity = response.getEntity();
                    if (null != entity) {
                        BufferedInputStream inputStream = new BufferedInputStream(entity.getContent());
                        FileUtils.copyInputStreamToFile(inputStream, file);
                        EntityUtils.consume(entity);
                    }
                }
            } catch (Exception e) {
            }
            ZInvoiceVo result = null;
            try {
                if (null != file) {
                    result = PdfInvoiceExtractor.extract(file);
//                    if (null != result.getAmount()) {
//                        file.delete();
//                    }
                } else {
                    result = new ZInvoiceVo();
                    result.setTitle("error");
                }
            } catch (IOException e) {
                e.printStackTrace();
                result = new ZInvoiceVo();
                result.setTitle("error");
            }
            // 将解析的数据添加到数据库中
            ZInvoice add = BeanUtil.toBean(result, ZInvoice.class);
//            baseMapper.insert()
            System.out.println("result:"+result);
        }
        return 0;
    }
}
